# -*- coding: UTF-8 -*-

import os
from multiprocessing import Process

from dash_lib.mongodb_helper import get_tipper_list_from_online, get_email_tipper_list_from_online


def run_py(array):
    os.system("python ./dash_lib/auto_fetch_tool.py " + " ".join(array))


def run_update_tipper_py():
    os.system("python ./auto_notify/fetch_tipper_list.py")


def spec_start(spect_tipper, max_count=3):
    query_array = [spect_tipper]
    thead_cout = max_count if len(query_array) > max_count else 1
    for thread_index in range(0, thead_cout):
        item_width = int(len(query_array) / thead_cout)
        params_array = query_array[item_width * thread_index:item_width * (thread_index + 1)]
        params_array.insert(0, str(thread_index))
        params = (" ").join(params_array)
        print(params)
        Process(target=run_py, args=(params_array,)).start()


def auto_start(is_only_email=False, max_pick_limit=2000, min_pick_limit=500, max_count=3):
    query_array = get_email_tipper_list_from_online() if is_only_email else get_tipper_list_from_online(min_pick_limit,
                                                                                                        max_pick_limit)
    # print(len(query_array), len(query_array))
    query_array.reverse()
    thead_cout = max_count if len(query_array) > max_count else 1
    for thread_index in range(0, thead_cout):
        item_width = int(len(query_array) / thead_cout)
        params_array = query_array[item_width * thread_index:item_width * (thread_index + 1)]
        params_array.insert(0, str(thread_index))
        params = (" ").join(params_array)
        print(params)
        Process(target=run_py, args=(params_array,)).start()


def start(commd, is_update_tipper_first=False):
    if is_update_tipper_first:
        run_update_tipper_py()
    if commd == 1:
        # all fetch
        auto_start(is_only_email=False)
    elif commd == 2:
        # only email
        auto_start(is_only_email=True)
    else:
        spec_start(commd)


start('topolski-tennis',is_update_tipper_first=False)
